package com.zrrd.yunchmall.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.yunchmall.order.client.AdminServiceClient;
import com.zrrd.yunchmall.order.client.ProductServiceClient;
import com.zrrd.yunchmall.order.entity.Order;
import com.zrrd.yunchmall.order.service.IOrderItemService;
import com.zrrd.yunchmall.order.service.IOrderOperateHistoryService;
import com.zrrd.yunchmall.order.service.IOrderService;
import com.zrrd.yunchmall.user.entity.Admin;
import com.zrrd.yunchmall.util.JwtUtil;
import com.zrrd.yunchmall.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author LYY
 * @since 2024-01-15
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/order")
@Api("订单服务接口")
public class OrderController {

    @Autowired
    private ProductServiceClient productServiceClient;

    @Autowired
    private AdminServiceClient adminServiceClient;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private IOrderOperateHistoryService orderOperateHistoryService;

    @PostMapping("/update/moneyInfo")
    @ApiOperation("修改费用信息")
    private ResponseResult updateMoneyInfo(@RequestBody Map<String,Object>params,@RequestHeader("Authorization") String token){
        Admin admin=JwtUtil.parseAdminToken(token.substring(7));
        orderService.updateMoneyInfo(params,admin);
        return new ResponseResult<>(200,"修改费用成功!");
    }

    @PostMapping("/update/receiverInfo")
    @ApiOperation("修改收货人信息")
    private ResponseResult updateReceiverInfo(@RequestBody Map<String,Object>params,Admin admin){
        orderService.updateReceiverInfo(params,admin);
        return new ResponseResult<>(200,"修改成功!");
    }

    @GetMapping("/list")
    @ApiOperation("查询所以订单")
    public ResponseResult list(@RequestParam int pageNum,
                               @RequestParam int pageSize,
                               String orderSn,
                               String receiverKeyword,
                               Integer status,
                               Integer orderType,
                               Integer sourceType,
                               String createTime) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //过滤掉已删除的订单
        queryWrapper.ne("delete_status",1);
        if (!StringUtils.isEmpty(orderSn)) {
            queryWrapper.eq("order_sn", orderSn);
            //在查询的语句结尾拼接一个limit 1，提高查询效率
            queryWrapper.last("limit 1");
            List<Order>orderList=orderService.list(queryWrapper);
            IPage page=new Page(pageNum,pageSize);
            page.setTotal(orderList.size());
            page.setRecords(orderList);
            return new ResponseResult<>(200,"查询成功!",page);
        } else {
            if (!StringUtils.isEmpty(receiverKeyword)) {
                String regStr="^1[3-9]\\d{9}$";
                //正则表达式的API Pattern(解析正则表达式)和Matcher(匹配字符串是不是符合正则表达式)
                Pattern pattern=Pattern.compile(regStr);
                Matcher matcher=pattern.matcher(receiverKeyword);
                //提供的关键字是手机号
                if (matcher.matches()){
                    queryWrapper.eq("receiver_phone",receiverKeyword);
                }else {
                    queryWrapper.eq("receiver_name",receiverKeyword);
                }
            }
            if (status!=null){
                queryWrapper.eq("status",status);
            }
            if (orderType!=null){
                queryWrapper.eq("order_type",orderType);
            }
            if (sourceType!=null){
                queryWrapper.eq("source_type",sourceType);
            }
            if (!StringUtils.isEmpty(createTime)){
                String start=createTime + " 00:00:00";
                String end=createTime + " 23:59:59";
                queryWrapper.between("create_time",start,end);
            }
        }
        return new ResponseResult<>(200,"查询成功!",
                orderService.page(new Page<>(pageNum,pageSize),queryWrapper
        ));
    }

    @GetMapping("/{orderId}")
    @ApiOperation("查看订单")
    private ResponseResult result(@PathVariable("orderId") Integer orderId){
        Order order=orderService.getById(orderId);
        QueryWrapper queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("order_id",orderId);
        order.setOrderItemList(orderItemService.list(queryWrapper));
        order.setHistoryList(orderOperateHistoryService.list(queryWrapper));

        return new ResponseResult<>(200,"查询成功",order);
    }
    @PostMapping("/update/close")
    @ApiOperation("关闭订单")
    public ResponseResult updateClose(@RequestParam String ids,@RequestParam String note){
        orderService.closeOrder(ids,note);
        //查询订单中的优惠卷金额，如果下单的商品中使用了优惠卷返还给消费者
        return new ResponseResult<>(200,"修改成功!");
    }
    @PostMapping("/update/delivery")
    @ApiOperation("订单发货")
    private ResponseResult updateDelivery(@RequestBody List<Map<String,Object>>params){
        orderService.delivery(params);
        return new ResponseResult<>(200,"执行成功!");
    }
    @PostMapping("/delete")
    @ApiOperation("订单发货")
    private ResponseResult updateDelete(@RequestParam String ids,
                                        @RequestHeader("Authorization") String token){
        //从token请求头中解析出当前登录的管理员信息(id和username)
        Admin admin= JwtUtil.parseAdminToken(token.substring(7));
        orderService.remove(ids,admin);
        return new ResponseResult<>(200,"执行成功!");
    }
    @GetMapping("/testSleuth")
    @ApiOperation("测试链路追踪")
    public String testSleuth() {
        System.out.println(productServiceClient.testSleuth());
        System.out.println(adminServiceClient.testSleuth());
        return "订单:测试链路追踪";
    }

}
